package com.unlcn.ils.sales.backend.service;

import cn.huiyunche.commons.constant.QiniuConstant;
import cn.huiyunche.commons.utils.QiniuUtil;
import com.google.common.collect.Lists;
import com.unlcn.ils.sales.backend.bo.BannerBO;
import com.unlcn.ils.sales.base.mapper.SaleBannerMapper;
import com.unlcn.ils.sales.base.model.SaleBanner;
import com.unlcn.ils.sales.base.model.SaleBannerExample;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created by houjianhui on 2017/6/10.
 */
@Service
public class BannerServiceImpl implements BannerService {

    private static final Logger LOGGER = LoggerFactory.getLogger(BannerServiceImpl.class);

    @Autowired
    private SaleBannerMapper bannerMapper;

    @Override
    public List<BannerBO> listBanner(String clientType, String appType, String w, String h) throws Exception {
        LOGGER.info("BannerServiceImpl.listBanner params clientType: {}, appType: {}, w: {}, h: {}", clientType, appType, w, h);
        if (StringUtils.isBlank(clientType)) {
            LOGGER.info("BannerServiceImpl.listBanner param clientType must not be null");
            throw new IllegalArgumentException("客户端类型不能为空");
        } else if (StringUtils.isBlank(appType)) {
            LOGGER.info("BannerServiceImpl.listBanner param appType must not be null");
            throw new IllegalArgumentException("应用类型不能为空");
        }

        SaleBannerExample example = new SaleBannerExample();
        example.createCriteria().andClientTypeEqualTo(clientType).andAppTypeEqualTo(appType);
        List<SaleBanner> banners = bannerMapper.selectByExample(example);
        List<BannerBO> bos = Lists.newArrayList();

        if (CollectionUtils.isNotEmpty(banners)) {
            banners.stream().forEach(val -> {
                BannerBO bo = new BannerBO();
                BeanUtils.copyProperties(val, bo);
                String treatMethod = "1", w1 = w, h1 = h;
                if (StringUtils.isBlank(w1) || StringUtils.isBlank(h1)) {
                    w1 = "";
                    h1 = "";
                    treatMethod = "";
                }
                bo.setPicUrl(QiniuUtil.generateDownloadURL(QiniuConstant.QINIU_DOWNLOAD_ADDRESS, val.getPicKey(),treatMethod, w1, h1));
                bos.add(bo);
            });
        }
        return bos;
    }
}
